"use client"

import { CalendarDate } from "@internationalized/date";
import { getClockRecord } from "@/api/flag/clock";
import { selectFlagClockRecordDetail, setFlagClockRecord, updateFlagClockRecord } from "@/lib/features/flag/flagSlice";
import { selectUserDetail } from "@/lib/features/login/loginSlice"
import { useAppDispatch, useAppSelector } from "@/lib/hooks"
import { AddFlagParams, FlagRecord } from "@/type/flag";
import { Button, RangeCalendar, Avatar, Image, useDisclosure, Modal, ModalContent, ModalHeader, ModalBody, Input, ModalFooter } from "@nextui-org/react";
import { useEffect, useState } from "react";
import { I18nProvider } from "@react-aria/i18n";
import toast from "react-hot-toast";
import { uploadFileImage } from "@/api/flag/uploadfile";
import { checkTimeClock } from "@/api/flag/check";
import { isLogin } from "@/api/user/authentication";

const RightIcon = ({ size, ...props }: { size: number }) => {
    return (
        <svg {...props}
            className="icon"
            viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1460" height={size || 24} width={size || 24}>
            <path d="M874 150C674.09-50 349.91-50 150 150s-200 524.09 0 724 524.09 200 724 0 200-524.09 0-724zM760.57 440.57l-256 256a80 80 0 0 1-113.14 0l-128-128a80 80 0 0 1 113.14-113.14L448 526.86l199.43-199.43a80 80 0 0 1 113.14 113.14z" fill="#ffffff" p-id="1461"></path></svg>
    )
}

const CurrentTime = () => {
    const [time, setTime] = useState(new Date().toLocaleTimeString());
    useEffect(() => {
        const interval = setInterval(() => {
            setTime(new Date().toLocaleTimeString()); // 格式化时间
        }, 1000); // 每秒更新一次
        return () => clearInterval(interval);
    })
    return (<>
        <span className="text-white font-bold text-opacity-80">{time}</span>
    </>)
}

const UploadFile = ({ isOpen, onOpenChange, clock }: { isOpen: boolean, onOpenChange: (value: boolean) => void, clock: (filePath: string) => void }) => {

    const [filePath, setFilePath] = useState("");

    const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files?.length) {
            const f: File = e.target.files[0]
            const result = await uploadFileImage(f)
            const str = await (result as Response).text()
            setFilePath(str);
        }
    };

    const clockToday = async (onClose: () => void) => {
        const result = await isLogin()
        if(result.code == 200){
            clock(filePath)
            onClose()
        }
    }

    return (
        <>
            <Modal isOpen={isOpen} placement="top-center" onOpenChange={onOpenChange}>
                <ModalContent>
                    {(onClose) => (
                        <>
                            <ModalHeader className="flex flex-col gap-1 text-white">Upload Image</ModalHeader>
                            <ModalBody>
                                <>
                                    {
                                        filePath != "" ? (
                                            <>
                                                <Image
                                                    isBlurred
                                                    alt="HeroUI Album Cover"
                                                    className="m-5"
                                                    src={'/api-backend' + filePath}
                                                    width={240}
                                                />
                                            </>
                                        ) : (
                                            <>
                                                {/* 限制只能选择图片 */}
                                                <Input
                                                    accept=".jpg,jepg,.png,.gif"
                                                    label="Image"
                                                    className="text-white"
                                                    placeholder="Enter your image"
                                                    onChange={handleFileChange}
                                                    variant="flat"
                                                    type="file"
                                                >
                                                </Input>
                                            </>
                                        )
                                    }
                                </>
                            </ModalBody>
                            <ModalFooter>
                                <Button color="primary" onPress={() => clockToday(onClose)}>
                                    Submit
                                </Button>
                            </ModalFooter>
                        </>
                    )}
                </ModalContent>
            </Modal>
        </>
    )
}

const FlagClockRecord = ({ flag_id }: { flag_id: number }) => {

    const { isOpen, onOpen, onOpenChange } = useDisclosure();

    const { email } = useAppSelector(selectUserDetail);

    const dispatch = useAppDispatch();
    const detail: AddFlagParams = useAppSelector((flag) => {
        return selectFlagClockRecordDetail(flag, flag_id)
    });

    useEffect(() => {

        let ignore = false;
        async function getClockData() {
            const result = await getClockRecord(email, flag_id)
            if (!ignore) {
                if (result.code == 200 && result.data.email == email) {
                    dispatch(setFlagClockRecord({ flagClockRecord: result.data.flagClockRecord, flag_id: flag_id }))
                }
            }
        }
        getClockData()
        return () => {
            ignore = true
        }
    }, [email, flag_id, dispatch])

    const getMinDate = () => {
        const date = new Date(detail.start ?? "")
        return new CalendarDate(date.getFullYear(), date.getMonth() + 1, date.getDate())
    }

    const getMaxDate = () => {
        const date = new Date(detail.period ?? "")
        return new CalendarDate(date.getFullYear(), date.getMonth() + 1, date.getDate())
    }

    // const getClockDateEnd = () => {
    //     const list = detail.list ?? []
    //     if(list.length == 0) return new CalendarDate(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate())
    //     const date = new Date(list[list.length - 1].clock_time ?? "")
    //     return new CalendarDate(date.getFullYear(), date.getMonth() + 1, date.getDate())
    // }

    // const getClockDateStart = () => {
    //     const list = detail.list ?? []
    //     if(list.length == 0) return new CalendarDate(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate())
    //     const date = new Date(list[0].clock_time ?? "")
    //     return new CalendarDate(date.getFullYear(), date.getMonth() + 1, date.getDate())
    // }

    const getClockTimeList = () => {
        return detail.list ?? []
    }

    const isTolete = (): boolean => {
        if (detail.checktime == null || detail.checktime == "" || detail.checktime == undefined) return false
        const now = new Date()
        const ct = new Date(now.toLocaleDateString() + ' ' + detail.checktime)
        return ct.getTime() < now.getTime()
    }

    const isClocking = () => {
        const list = detail.list ?? []
        if (list.length == 0) return false
        const clock_time = list[list.length - 1].clock_time
        if (clock_time == null || clock_time == "" || clock_time == undefined) return false
        const now = new Date()
        const ct = new Date(clock_time)
        return now.toLocaleDateString() == ct.toLocaleDateString()
    }

    const checkTimeCLockHandler = async (fcrt: FlagRecord) => {
        const result = await checkTimeClock(fcrt)
        toast.dismiss()
        if (result.code == 200) {
            dispatch(updateFlagClockRecord(fcrt))
            toast.success(result.message)
        } else {
            toast.error(result.message)
        }
    }

    const clock = async (filePath: string) => {
        const list = getClockTimeList()
        const cd = new Date();
        const st = new Date(detail.start ?? "")
        const et = new Date(detail.period ?? "")
        const ct = new Date((cd.toLocaleDateString() + ' ' + detail.checktime))
        const fcrt: FlagRecord = {
            clock_id: list.length + 1,
            f_id: flag_id,
            clock_type: detail.mode,
            clock_attachments: filePath ?? null
        }
        toast.dismiss()
        if (cd.getTime() > st.getTime() && cd.getTime() < et.getTime()) {
            const clockingTime = (cd.toLocaleDateString() + ' ' + cd.toLocaleTimeString()).replaceAll('/', '-')
            fcrt.clock_time = clockingTime
            if (cd.getTime() > (ct.getTime() - 3600000)) {
                if (list.length == 0) {
                    checkTimeCLockHandler(fcrt)
                } else {
                    if (!detail.over) {
                        checkTimeCLockHandler(fcrt)
                    }
                }
            } else {
                if (detail.checktime == null || detail.checktime == "" || detail.checktime == undefined) {
                    checkTimeCLockHandler(fcrt)
                } else {
                    if (cd.getTime() > (ct.getTime() - 3600000)) {
                        checkTimeCLockHandler(fcrt)
                    } else {
                        toast.error("打卡时间太早了")
                    }
                }
            }
        } else {
            if (cd.getTime() > et.getTime()) {
                toast.error("已经完结撒花了")
            } else {
                toast.error("计划暂未启动")
            }
        }

    }

    return (
        <>
            <UploadFile clock={clock} isOpen={isOpen} onOpenChange={onOpenChange} />
            <I18nProvider locale="zh-CN-u-ca-chinese">
                <RangeCalendar
                    classNames={{
                        errorMessage: "hidden"
                    }}
                    topContent={
                        <div className="text-sm flex justify-center py-2 text-gray-500">
                            {detail.description}
                        </div>
                    }
                    bottomContent={
                        <>
                            <p className="text-sm py-1 bg-black text-white text-center">{detail.checktime}</p>
                            <div className="text-sm flex justify-center py-2 text-gray-500">
                                {
                                    !isTolete() && !isClocking() && !detail.over ? (
                                        <Button color="warning" onPress={() => onOpen()}>
                                            <CurrentTime />
                                        </Button>
                                    ) : (
                                        isClocking() && !detail.over ? (
                                            <Avatar size="sm" isBordered color="success" isDisabled radius="sm" icon={
                                                <>
                                                    <RightIcon size={28} />
                                                </>
                                            } />
                                        ) : (
                                            <Button isDisabled={true} color="danger">
                                                {
                                                    detail.over ? (<span>It&apos;s Over</span>) : (<span>It&apos;s too late Or Do not start</span>)
                                                }
                                            </Button>
                                        )
                                    )
                                }

                            </div>
                        </>
                    }
                    // minValue={getMinDate()}
                    // maxValue={getMaxDate()}
                    color="success"
                    value={{
                        start: getMinDate(),
                        end: getMaxDate()
                    }}
                    isReadOnly
                    allowsNonContiguousRanges
                    isDateUnavailable={(date) => {
                        let f = false
                        getClockTimeList().forEach((item) => {
                            const dt = new Date(date.toString())
                            const ct = new Date(item.clock_time ?? "")
                            if (ct.toLocaleDateString() == dt.toLocaleDateString()) {
                                return f = true
                            }
                        })
                        return f
                    }}
                >

                </RangeCalendar>
            </I18nProvider>
        </>
    )
}
export default FlagClockRecord